﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;

namespace TurboTemplate
{
    public static class SerializationExtensionMethods
    {

        public static T Load<T>(this string file) where T : class
        {
            DataContractSerializer dc = new DataContractSerializer(typeof(T));

            using (var f = System.IO.File.Open(file, System.IO.FileMode.Open))
            {
                try
                {
                    var ret = dc.ReadObject(f) as T;
                    return ret as T;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

        public static void Save<T>(this T instance, string file)
        {
            DataContractSerializer dc = new DataContractSerializer(typeof(T));

            // Save to memory first, then dump to file only if there are no errors
            using(MemoryStream ms = new MemoryStream())
            {
                try
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(ms, Encoding.UTF8))
                    {
                        using (System.Xml.XmlTextWriter tw = new System.Xml.XmlTextWriter(sw))
                        {
                            tw.Formatting = System.Xml.Formatting.Indented;
                            dc.WriteObject(tw, instance);
                        }
                    }
                    File.WriteAllBytes(file, ms.ToArray());
                }
                catch (Exception)
                {
                    // Do nothing.
                }
            }
        }

    }
}
